package cn.harry.modular.ai.controller;

import cn.harry.common.api.R;
import cn.harry.common.utils.BeanUtils;
import cn.harry.component.security.utils.SecurityUtils;
import cn.harry.modular.ai.domain.ChatConversation;
import cn.harry.modular.ai.domain.ChatMessage;
import cn.harry.modular.ai.service.ChatConversationService;
import cn.harry.modular.ai.service.ChatMessageService;
import cn.harry.modular.ai.service.ChatRoleService;
import cn.harry.modular.ai.vo.message.AiChatMessageRespVO;
import cn.harry.modular.ai.vo.message.AiChatMessageSendReqVO;
import cn.harry.modular.ai.vo.message.AiChatMessageSendRespVO;
import cn.hutool.core.util.ObjUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Collections;
import java.util.List;


@Tag(name = "管理后台 - 聊天消息")
@RestController
@RequestMapping("/ai/chat/message")
@Slf4j
public class AiChatMessageController {

    @Resource
    private ChatMessageService chatMessageService;
    @Resource
    private ChatConversationService chatConversationService;
    @Resource
    private ChatRoleService chatRoleService;

    @Operation(summary = "发送消息（段式）", description = "一次性返回，响应较慢")
    @PostMapping("/send")
    public R<AiChatMessageSendRespVO> sendMessage(@Valid @RequestBody AiChatMessageSendReqVO sendReqVO) {
        Long userId = SecurityUtils.getUserId();
        return R.success(chatMessageService.sendMessage(sendReqVO, userId));
    }

    @Operation(summary = "发送消息（流式）", description = "流式返回，响应较快")
    @PostMapping(value = "/send-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @PermitAll // 解决 SSE 最终响应的时候，会被 Access Denied 拦截的问题
    public Flux<R<AiChatMessageSendRespVO>> sendChatMessageStream(@Valid @RequestBody AiChatMessageSendReqVO sendReqVO) {
        Long userId = SecurityUtils.getUserId();
        return chatMessageService.sendChatMessageStream(sendReqVO, userId);
    }

    @Operation(summary = "获得指定对话的消息列表")
    @GetMapping("/list-by-conversation-id")
    @Parameter(name = "conversationId", required = true, description = "对话编号", example = "1024")
    public R<List<AiChatMessageRespVO>> getChatMessageListByConversationId(
            @RequestParam("conversationId") Long conversationId) {
        Long userId = SecurityUtils.getUserId();
        ChatConversation conversation = chatConversationService.getById(conversationId);
        if (conversation == null || ObjUtil.notEqual(conversation.getUserId(), userId)) {
            return R.success(Collections.emptyList());
        }
        List<ChatMessage> messageList = chatMessageService.getChatMessageListByConversationId(conversationId);
        return R.success(BeanUtils.toBean(messageList, AiChatMessageRespVO.class));
    }

}
